
const fs = require('fs');
const path = require('path');
const router = require('koa-router')();

//传入目录获取文件
function getFiles(dir) {

    let file = fs.readdirSync(dir)

    return file.filter((x) => {
        return x.endsWith('.js') && x !== 'index.js'
    })

}

function getRoutes(files) {

    files.map((x) => {
        let routesMOd = require(path.join(__dirname, x))

        for (let r in routesMOd) {
            let type = routesMOd[r][0];
            let fn = routesMOd[r][1];

            if (type == "get") {
                router.get(r, fn)
            } else {
                router.post(r, fn)
            }
        }
    })
}

module.exports = function (dirName) {

    let dir = dirName || __dirname;

    let files = getFiles(dir)

    getRoutes(files)

    return router.routes();

}